package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.common.PageRequest;
import com.sky.dto.common.ParamsID;
import com.sky.dto.common.QueryParams;
import com.sky.entity.Dict;
import com.sky.entity.Instructor;
import com.sky.exception.CommonException;
import com.sky.mapper.DictMapper;
import com.sky.mapper.InstructorMapeer;
import com.sky.result.PageResult;
import com.sky.service.DicSercice;
import com.sky.utils.TreeUtils;
import com.sky.vo.DictVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DicServiceImpl implements DicSercice {
    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private InstructorMapeer instructorMapeer;
    /**
     * 获取字典分类下的对应的 分页数据
     * @param queryParams
     * @return
     */
    @Override
    public PageResult getDicData(PageRequest<QueryParams> queryParams) {
        PageHelper.startPage(queryParams.getPageNum(), queryParams.getPageSize());
        Page<Dict> page = dictMapper.getDicData(queryParams.getParams());
        Long total = page.getTotal();
        List<Dict> result = page.getResult();
        log.info("获取字典数据成功，total: {}, result size: {}", result);
        // 对result 数据开始构造tree
        List<DictVO> tree = result.stream()
                .map(dict -> {
                    DictVO vo = new DictVO();
                    BeanUtils.copyProperties(dict, vo);
                    vo.setChildren(getChildrenRecursive(dict.getId()));
                    return vo;
                }).collect(Collectors.toList());
        return new PageResult(total, tree);
    }

    /**
     * 增加字典数据
     * @param dict
     */
    @Override
    public void addDicData(Dict dict) {
        // 如果是数据字典，判断当前字典数据下的数据值value是否重复
        if(dict.getPid() != null && !"".equals(dict.getPid())){
            if(dict.getValue() != null){
                List<Dict> temp = dictMapper.getDicDataTreeById(dict.getPid());
                for (Dict item : temp) {
                    // 判断 value 是否重复，排除自己（用于更新时）
                    if (item.getValue().equals(dict.getValue())){
                        throw new CommonException("该字典分类下已存在相同的数据值！");
                    }
                }
            }
        }
        // 插入新的字典数据
        dictMapper.addDicData(dict);
        log.info("新增字典数据成功，dict: {}", dict);
    }

    /**
     * 更新字典数据
     * @param dict
     */
    @Override
    public void updateDicData(Dict dict) {
        // 更新字典数据
        if(dict.getPid() != null && !"".equals(dict.getPid())){
            if(dict.getValue() != null){
                List<Dict> temp = dictMapper.getDicDataTreeById(dict.getPid());
                for (Dict item : temp) {
                    // 判断 value 是否重复，排除自己（用于更新时）
                    if (Objects.equals(item.getValue(), dict.getValue())){
                        throw new CommonException("该字典分类下已存在相同的数据值！");
                    }
                }
            }
        }
        dictMapper.updateDicData(dict);
        log.info("更新字典数据成功，dict: {}", dict);
    }

    /**
     * 删除字典数据
     * @param ids
     */

    @Override
    public void deleteDicData(ParamsID ids) {
        // 获取当前线程的用户id
        String currentId = BaseContext.getCurrentId();
        Instructor info = instructorMapeer.getInfoById(currentId);
        if(info.getPermissionLevel() != 0){
            throw new CommonException(MessageConstant.POWER_ERR);
        }else{
            ids.getIds().forEach(id -> {
                if(dictMapper.countByPid(id) > 0) {
                    throw new CommonException(MessageConstant.DELETE_ERR);
                }
                dictMapper.deleteDicData(id);
            });
        }
    }

    /**
     * 获取字典分类列表
     * @return
     */
    @Override
    public PageResult getDicDataAll(PageRequest<QueryParams> queryParams) {
        log.info("获取字典分类列表，queryParams: {}", queryParams);
        PageHelper.startPage(queryParams.getPageNum(), queryParams.getPageSize());
        Page<Dict> page = dictMapper.getDicDataAll(queryParams.getParams());
        Long total = page.getTotal();
        List<Dict> result = page.getResult();
        log.info("获取字典分类列表成功，total: {}, result size: {}", total, result.size());
        return new PageResult(total, result);
    }

    @Override
    public List<DictVO> getDicDataTree(String dictCode) {
        List<Dict> result = dictMapper.getDicDataTree(dictCode);
        List<DictVO> tree = TreeUtils.buildTree(
                result,
                dict -> {
                    // 转换 Dict → DictVO
                    return DictVO.builder()
                            .id(String.valueOf(dict.getId()))
                            .pid(String.valueOf(dict.getPid()))
                            .name(dict.getName())
                            .dictCode(dict.getDictCode())
                            .desc(dict.getDesc())
                            .type(dict.getType())
                            .build();
                },
                DictVO::getId,
                DictVO::getPid,
                ArrayList::new,
                DictVO::getChildren,
                DictVO::setChildren
        );
        return tree;
    }
//======================================BEGIN 工具函数==================================
    private List<DictVO> getChildrenRecursive(String parentId) {
        List<Dict> children = dictMapper.getDicDataTreeById(parentId);
        if (children.isEmpty()) {
            return new ArrayList<>();
        }
        return children.stream().map(child -> {
            DictVO vo = new DictVO();
            BeanUtils.copyProperties(child, vo);
            vo.setChildren(getChildrenRecursive(child.getId()));
            return vo;
        }).collect(Collectors.toList());
    }
}
